package com.yuji.aacar.core.cores.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Toast;

/**
 * <li>Package:com.ttp.core.cores.utils
 * <li>Author: lining
 * <li>Date: 2017/5/4
 * <li>Description: Toast显示同一条的时候过滤
 */

public class CoreToast {

    private static String oldMsg;
    private static long time;

    public static void showToast(Context context, String msg) {
        // 当显示的内容不一样时，即断定为不是同一个Toast
        if (!msg.equals(oldMsg)) {
            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
            time = System.currentTimeMillis();
        } else {
            // 显示内容一样时，只有间隔时间大于2秒时才显示
            if (System.currentTimeMillis() - time > 2000) {
                Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
                time = System.currentTimeMillis();
            }
        }
        oldMsg = msg;
    }

    public static void showToast(Context context, String msg, int duration) {
        // 当显示的内容不一样时，即断定为不是同一个Toast
        if (!msg.equals(oldMsg)) {
            Toast.makeText(context, msg, duration).show();
            time = System.currentTimeMillis();
        } else {
            // 显示内容一样时，只有间隔时间大于2秒时才显示
            if (System.currentTimeMillis() - time > 2000) {
                Toast.makeText(context, msg, duration).show();
                time = System.currentTimeMillis();
            }
        }
        oldMsg = msg;
    }


    /**
     * 根据传入的toast背景色， 将toast显示在中间
     * @param context
     * @param msg
     * @param toastBackGroundResource
     */
    public static void showToastAtCenter (Context context, String msg, int toastBackGroundResource) {
        // 当显示的内容不一样时，即断定为不是同一个Toast
        if (!msg.equals(oldMsg)) {
            if (!TextUtils.isEmpty(msg)) {
                Toast toast = Toast.makeText(context, msg,Toast.LENGTH_LONG);
                ViewGroup layout = (ViewGroup) toast.getView();
                layout.setBackgroundResource(toastBackGroundResource);
                int padding = layout.getPaddingTop() / 2;
                layout.setPadding(padding, layout.getPaddingTop(), padding, layout.getPaddingBottom());
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                time = System.currentTimeMillis();
            }

        } else {
            // 显示内容一样时，只有间隔时间大于2秒时才显示
            if (System.currentTimeMillis() - time > 2000) {
                Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
                time = System.currentTimeMillis();
            }
        }
        oldMsg = msg;
    }

}
